package com.codeshellme.bookmanager.service;

import com.codeshellme.bookmanager.dao.UmsUserDao;
import com.codeshellme.bookmanager.dto.UmsUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

// 供 SecurityConfig 使用
@Service("userDetailsService")
public class AccessService implements UserDetailsService {

    @Autowired
    private UmsUserDao umsUserDao;

    /**
     * @param username 登录页面传过来的
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UmsUser user = umsUserDao.findByUserName(username);
        if (user == null) {
            // 没有找到用户
            throw new UsernameNotFoundException("用户不存在");
        }

        // 授权，授予角色
        List<GrantedAuthority> anths = AuthorityUtils.commaSeparatedStringToAuthorityList(
                "ROLE_" + user.getRole_id());

        return new User(
                user.getUsername(),
                new BCryptPasswordEncoder().encode(user.getPassword()),
                anths);
    }

}